﻿using System.Collections.Generic;
using System.Windows.Forms;

namespace DotNet.Common
{
    abstract public class DynamicPanel<toolControl> : Panel
        where toolControl : DynamicUserControl, IDynamicOperation, new()
    {
        public event ControlHandler OnAdd;
        bool m_modified;

        public bool Modified
        {
            get { return m_modified; }
            set { m_modified = value; }
        }

        public DynamicPanel()
        {
            m_modified = false;
            this.AutoScroll = true;
            this.Add();
        }

        abstract protected void Initialize();

        protected toolControl Add()
        {
            toolControl oControl = new toolControl();

            oControl.Location = new System.Drawing.Point(0, oControl.Height * this.Controls.Count - this.VerticalScroll.Value);
            oControl.OnAdd += Add;
            oControl.OnDelete += Delete;

            this.Controls.Add(oControl);

            if (OnAdd != null)
                OnAdd(oControl);

            oControl.Num = this.Controls.Count;

            m_modified = true;
            oControl.Focus();
            return oControl;
        }

        protected void Delete(UserControl control)
        {
            if (this.Controls.Count > 1)
            {
                int index = this.Controls.IndexOf(control);
                {
                    this.Controls.Remove(control);
                }
                if (index == this.Controls.Count)
                    index--;
                this.Controls[index].Focus();

                Update();
            }
            else
            {
                (control as IDynamicOperation).Empty();
            }
            m_modified = true;
        }

        private new void Update()
        {
            int index = 0;
            foreach (toolControl control in this.Controls)
            {
                control.Location = new System.Drawing.Point(0, control.Height * index);
                index++;

                control.Num = index;
            }

            base.Update();
        }

        protected void Clear()
        {
            this.Controls.Clear();
            m_modified = true;
        }
    }
}
